<?php
/*
 * DB manager class
 */

class DBmanager
{
    private $LAST_INSERTED_ID;
    private $ROW_COUNT;
     
    /**
     * Enter description here ...
     */
    public function __construct()
    {
        global  $CONFIG;
        
        $server_db = $CONFIG->database->host;
        $username_db = $CONFIG->database->user;
        $password_db = $CONFIG->database->password;
        $name_db = $CONFIG->database->dbname;
        if ($_SERVER['REMOTE_ADDR'] == '150.101.230.130' && !empty($CONFIG->devdatabase)) {
            $server_db = $CONFIG->devdatabase->host;
            $username_db = $CONFIG->devdatabase->user;
            $password_db = $CONFIG->devdatabase->password;
            $name_db = $CONFIG->devdatabase->dbname;
        }
        $dbConnString =  "mysql:host=" . $server_db . "; dbname=" .$name_db ;
        $this->PDO = new PDO($dbConnString, $username_db, $password_db, [PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES'utf8';"]);
        $error = $this->PDO->errorInfo();
        if ($this->PDO->errorCode()!='000000') {
            die(var_dump($error));
        }
        
        /*old connection
		$link = @mysql_connect($server_db, $username_db, $password_db);
		if(!$link) {
			echo implode(',', $this->PDO->errorInfo());
			die('Could not connect to server');
		}
		if(!@mysql_select_db($name_db))	{
			die("Could not select database");
		}
		*/
    }

    /**
     * Enter description here ...
     * @param unknown_type $MySQL
     * @return void|resource
     */
    public function executeSQL($MySQL, $params = array())
    {
        try {
            if (empty($MySQL)) {
                return false;
            }
            $this->queryresult = true;
            $this->PDO->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            if ($STH = $this->PDO->prepare($MySQL)) {
                foreach ($params as $key => &$val) {
                    $STH->bindParam(":{$key}", $val);
                }
                $execute_res = $STH->execute($params);
                if ($execute_res === false) {
                    $err = print_r($this->PDO->errorInfo(), 1);
                    $trace = debug_backtrace();
                    $backtrace = parse_backtrace($trace);
                    $errMsg = logError($backtrace, $err, $MySQL);
                    $this->queryresult = false;
                    header('Location: /404');
                    $errno = error_get_last();
                    $body = "<table><thead bgcolor='#c8c8c8'><th>Item</th><th>Description</th></thead><tbody>";
                    $body .= "<tr valign='top'><td><b>Error</b></td><td><pre>{$errno['message']}</pre></td></tr>";
                    $body .= "<tr valign='top'><td><b>Errno</b></td><td><pre>{$errno['type']}</pre></td></tr>";
                    $body .= "<tr valign='top'><td><b>File</b></td><td>{$errno['file']}</td></tr>";
                    $body .= "<tr valign='top'><td><b>Line</b></td><td>{$errno['line']}</td></tr>";
                    $body .= "<tr valign='top'><td><b>Line</b></td><td>{$errno['line']}</td></tr>";
                    $body .= '</tbody></table>';
                    $body .= '<br />DATABASE<br/>';
                    $body .= print_r($this->PDO->errorInfo(), 1);
                    $body .= '<br />$_POST<br/>';
                    $body .= print_r($_POST, true);
                    $body .= '<br />$_SERVER<br/>';
                    $body .= print_r($_SERVER, true);
                    $subject = "Database Error";
                    $to = "readysteadygokids@gmail.com";
                    $from = "RSGK - Australia";
                    $fromEmail = 'noreply@' . str_replace("www.", "", $_SERVER['HTTP_HOST']);
                    /* To send HTML mail, you can set the Content-type header. */
                    $headers  = "MIME-Version: 1.0\r\n";
                    $headers .= "Content-type: text/html; charset=iso-8859-1\r\n";
                    $headers .= "X-Priority: 3\r\n";
                    $headers .= "X-Mailer: PHP". phpversion() ."\r\n";
                    /* additional headers */
                    $headers .= "Reply-To: ". $from . " <".$fromEmail.">\r\n";
                    $headers .= "Return-Path: ". $from . " <".$fromEmail.">\r\n";
                    $headers .= "From: ". $from . " <".$fromEmail.">\r\n";
                    $headers .= "Bcc: readysteadygokids@bccgmail.com\r\n";
                    if ($_SERVER['REMOTE_ADDR']=='192.168.10.1') {
                        die($body);
                    } else {
                      //include_once '/database/safemail.php';
                      //SafeMail($to,$subject,$body,$headers);
                    }
                
                    die();
                }
                $this->LAST_INSERTED_ID =  $this->PDO->lastInsertId();
                $this->ROW_COUNT =  $STH->rowCount();
                $this->lastquery = $MySQL;
                try {
                    $result = $STH->fetchAll(PDO::FETCH_ASSOC);
                    $this->lastresult = $result;
                } catch (Exception $e) {
                    $result = $execute_res;
                }
                return $result;
            }
        } catch (Exception $e) {
            //var_dump($e);exit;
            if ($e instanceof PDOException) {
                $body = "<table><thead bgcolor='#c8c8c8'><th>Item</th><th>Description</th></thead><tbody>";
                $body .= "<tr valign='top'><td><b>Error</b></td><td><pre>{$e->getMessage()}</pre></td></tr>";
                $body .= "<tr valign='top'><td><b>Errno</b></td><td><pre>{$e->getCode()}</pre></td></tr>";
                $body .= "<tr valign='top'><td><b>File</b></td><td>{$e->getFile()}</td></tr>";
                $body .= "<tr valign='top'><td><b>Line</b></td><td>{$e->getLine()}</td></tr>";
                $body .= '</tbody></table>';
                $body .= '<br />TRACE<br/><pre>';
                $body .= print_r($e->getTrace(), 1);
                $body .= '</pre><br />DATABASE<br/><pre>';
                $body .= print_r($this->PDO->errorInfo(), 1);
                $body .= '</pre><br />$_POST<br/><pre>';
                $body .= print_r($_POST, true);
                $body .= '</pre><br />$_SERVER<br/><pre>';
                $body .= print_r($_SERVER, true).'</pre>';
            } else {
                $errno = error_get_last();
                $body = "<table><thead bgcolor='#c8c8c8'><th>Item</th><th>Description</th></thead><tbody>";
                $body .= "<tr valign='top'><td><b>Error</b></td><td><pre>{$errno['message']}</pre></td></tr>";
                $body .= "<tr valign='top'><td><b>Errno</b></td><td><pre>{$errno['type']}</pre></td></tr>";
                $body .= "<tr valign='top'><td><b>File</b></td><td>{$errno['file']}</td></tr>";
                $body .= "<tr valign='top'><td><b>Line</b></td><td>{$errno['line']}</td></tr>";
                $body .= "<tr valign='top'><td><b>Line</b></td><td>{$errno['line']}</td></tr>";
                $body .= '</tbody></table>';
                $body .= '<br />DATABASE<br/>';
                $body .= print_r($this->PDO->errorInfo(), 1);
                $body .= '<br />$_POST<br/>';
                $body .= print_r($_POST, true);
                $body .= '<br />$_SERVER<br/>';
                $body .= print_r($_SERVER, true);
            }
            $subject = "Database Error";
            $to = "readysteadygokids@gmail.com";
            $from = "RSGK - Australia";
            $fromEmail = 'noreply@' . str_replace("www.", "", $_SERVER['HTTP_HOST']);
            /* To send HTML mail, you can set the Content-type header. */
            $headers  = "MIME-Version: 1.0\r\n";
            $headers .= "Content-type: text/html; charset=iso-8859-1\r\n";
            $headers .= "X-Priority: 3\r\n";
            $headers .= "X-Mailer: PHP". phpversion() ."\r\n";
            /* additional headers */
            $headers .= "Reply-To: ". $from . " <".$fromEmail.">\r\n";
            $headers .= "Return-Path: ". $from . " <".$fromEmail.">\r\n";
            $headers .= "From: ". $from . " <".$fromEmail.">\r\n";
            $headers .= "Bcc: readysteadygokids@bccgmail.com\r\n";
            if ($_SERVER['REMOTE_ADDR']=='192.168.10.1') {
                  die($body);
            } else {
                //include_once '/database/safemail.php';
                //SafeMail($to,$subject,$body,$headers);
            }
        }
    }

    /**
     * Enter description here ...
     */
    public function wrappedSqlIdentity()
    {
        return $this->LAST_INSERTED_ID;
    }

    /**
     * Enter description here ...
     */
    public function wrappedSqlRowcount()
    {
        return $this->ROW_COUNT;
    }

    /**
     * Enter description here ...
     * @param unknown_type $sql
     * @return Ambigous <void, resource>
     */
    public function wrappedSqlInsert($sql, $params = array())
    {
        $result = $this->executeSQL($sql, $params);
        if ($this->PDO->errorCode()!='000000') {
            $err = implode(',', $this->PDO->errorInfo());
            $trace = debug_backtrace();
            $backtrace = parse_backtrace($trace);
            $errMsg = logError($backtrace, $err, $sql);
            header('Location: /404');
        }
        return $result;
    }

    /**
     * Enter description here ...
     * @param unknown_type $sql
     * @return string|boolean
     */
    public function wrappedSqlGetSingle($sql, $params = array())
    {
        $result = $this->executeSQL($sql, $params);
        if ($this->PDO->errorCode()!='000000') {
            $err = implode(',', $this->PDO->errorInfo());
            $trace = debug_backtrace();
            $backtrace = parse_backtrace($trace);
            $errMsg = logError($backtrace, $err, $sql);
            header('Location: /404');
            die();
        }
        if ($result) {
            return $result[0];
        } else {
            return false;
        }
    }
    /**
     * Enter description here ...
     * @param unknown_type $sql
     * @return multitype:|boolean
     */
    public function wrappedSqlGet($sql, $params = array())
    {
        $result = $this->executeSQL($sql, $params);
        if ($this->PDO->errorCode()!='000000') {
            $err = implode(',', $this->PDO->errorInfo());
            $trace = debug_backtrace();
            $backtrace = parse_backtrace($trace);
            $errMsg = logError($backtrace, $err, $sql);
            header('Location: /404');
        }
        if (!empty($result)) {
            return $result;
        } else {
            return [];
        }
    }

    /**
     * Enter description here ...
     * @param unknown_type $sql
     * @return multitype:|boolean
     */
    public function wrappedSql($sql, $params = array())
    {
        $result = $this->executeSQL($sql, $params);
        if ($this->PDO->errorCode()!='000000') {
            $err = implode(',', $this->PDO->errorInfo());
            $trace = debug_backtrace();
            $backtrace = parse_backtrace($trace);
            $errMsg = logError($backtrace, $err, $sql);
            header('Location: /404');
        }
        if (!empty($result)) {
            return $result;
        } else {
            return false;
        }
    }

    /**
     * Enter description here ...
     * @param unknown_type $table
     * @return multitype:
     */
    public function ShowColumns($table)
    {
        $sql =  "SHOW COLUMNS FROM ".$table;
        if ($sql_res = $this->executeSQL($sql)) {
            if (!empty($sql_res)) {
                return $result;
            } else {
                return false;
            }
        }
    }
    public function ShowTables()
    {
        $sql = "SHOW TABLES";
        $arr = $this->wrappedSqlGet($sql);
        foreach ($arr as $table_a) {
            foreach ($table_a as $table) {
                $tables[]=$table;
            }
        }
        return $tables;
    }

    /**
     * Enter description here ...
     * @param unknown_type $string
     * @return string
     */
    public function SQLdatetoOZformat($string)
    {
        $arrray = explode("-", $string);
        $date = $arrray[2]."/".$arrray[1]."/".$arrray[0];
        return $date;
    }

    /**
     * Enter description here ...
     * @param unknown_type $string
     * @return string
     */
    public function SQLdatetimetoOzFormat($string)
    {
        $date = explode(" ", $string);
        $newdate = SQLdatetoOZformat($date[0]);
        $newdate .=" ".$date[1];
        return $newdate;
    }
}
